<template>
  <div class="edit-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑库存' : '新增库存' }}</span>
          <el-button @click="router.back()">返回</el-button>
        </div>
      </template>

      <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          style="max-width: 800px;"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="药材" prop="herbId">
              <el-select
                  v-model="form.herbId"
                  placeholder="请选择药材"
                  style="width: 100%"
                  :disabled="isEdit || prefillHerbId"
                  filterable
              >
                <el-option
                    v-for="herb in herbList"
                    :key="herb.herbId"
                    :label="herb.herbName"
                    :value="herb.herbId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNumber">
              <el-input v-model="form.batchNumber" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker
                  v-model="form.purchaseDate"
                  type="date"
                  placeholder="选择采购日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过期日期" prop="expirationDate">
              <el-date-picker
                  v-model="form.expirationDate"
                  type="date"
                  placeholder="选择过期日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input-number
                  v-model="form.quantity"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
                  placeholder="请输入数量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number
                  v-model="form.unitPrice"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
                  placeholder="请输入单价"
                  prefix="￥"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存储位置" prop="storageLocation">
              <el-input v-model="form.storageLocation" placeholder="请输入存储位置" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="质量备注" prop="qualityNotes">
          <el-input
              v-model="form.qualityNotes"
              type="textarea"
              :rows="3"
              placeholder="请输入质量备注"
          />
        </el-form-item>

        <el-form-item label="状态" prop="isAvailable">
          <el-switch v-model="form.isAvailable" />
          <span style="margin-left: 10px;">{{ form.isAvailable ? '可用' : '不可用' }}</span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
          <el-button @click="router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { herbInventoryApi, chineseHerbApi } from '@/api/admin'

const route = useRoute()
const router = useRouter()
const formRef = ref()
const loading = ref(false)
const herbList = ref([])

const isEdit = computed(() => route.params.id !== undefined)
const prefillHerbId = computed(() => route.query.herbId)

const form = reactive({
  inventoryId: null,
  herbId: null,
  batchNumber: '',
  purchaseDate: '',
  expirationDate: '',
  quantity: 0,
  unitPrice: 0,
  supplierName: '',
  storageLocation: '',
  qualityNotes: '',
  isAvailable: true
})

const rules = {
  herbId: [
    { required: true, message: '请选择药材', trigger: 'change' }
  ],
  batchNumber: [
    { required: true, message: '请输入批次号', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, message: '请输入单价', trigger: 'blur' }
  ]
}

const loadHerbs = async () => {
  try {
    // 获取所有药材用于下拉选择
    const res = await chineseHerbApi.page('', null, 1, 10)
    herbList.value = res.data.records || []
  } catch (error) {
    ElMessage.error('加载药材列表失败')
  }
}

const loadInventoryDetail = async (id) => {
  try {
    const res = await herbInventoryApi.getById(id)
    Object.assign(form, res.data)
    // 转换日期格式
    if (form.purchaseDate) {
      form.purchaseDate = formatDateForPicker(form.purchaseDate)
    }
    if (form.expirationDate) {
      form.expirationDate = formatDateForPicker(form.expirationDate)
    }
  } catch (error) {
    ElMessage.error('加载库存详情失败')
    router.back()
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    loading.value = true
    try {
      if (isEdit.value) {
        await herbInventoryApi.update(form)
        ElMessage.success('更新成功')
      } else {
        await herbInventoryApi.add(form)
        ElMessage.success('创建成功')
      }
      router.push('/admin/herb-inventory')
    } catch (error) {
      ElMessage.error('操作失败')
    } finally {
      loading.value = false
    }
  })
}

const formatDateForPicker = (date) => {
  if (!date) return ''
  return new Date(date).toISOString().split('T')[0]
}

onMounted(() => {
  loadHerbs()

  // 如果是编辑模式，加载库存详情
  if (isEdit.value) {
    loadInventoryDetail(route.params.id)
  }
  // 如果是新增模式且有预填的药材ID，设置药材ID
  else if (prefillHerbId.value) {
    form.herbId = parseInt(prefillHerbId.value)
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
